package com.pswv2.backstage.keyword.action;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.omg.CORBA.portable.InputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.aliyun.oss.model.Style;
import com.pswv2.backstage.keyword.service.KWordService;
import com.pswv2.bub.bsc.dao.po.KWord;
import com.pswv2.bub.bsc.dao.po.ShareKWord;
import com.pswv2.bub.bsc.dao.po.User;
import com.pswv2.util.BackendErrorCode;
import com.pswv2.util.CommonResp;
import com.pswv2.util.ExtraSpringHibernateTemplate;
import com.pswv2.util.Paging;
import com.pswv2.util.Sessions;
import com.pswv2.util.Strings;

@Controller
@RequestMapping(value = "keysAcion", produces = { "text/json;charset=UTF-8" })
public class KWordAction {
	private static Class<?> poc = KWord.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private KWordService kWordService;
	
	/**
	 * 选择的返回信息
	 */
	@ResponseBody
	@RequestMapping(value = { "pitchOnData" })
	public String pitchOnData(String items) {
		List<KWord> ls=new ArrayList<KWord>();
		String[] arr = items.split(",");
		for(String a:arr){
			KWord keyword = kWordService.queryById(Integer.parseInt(a));
			ls.add(keyword);
		}
		return CommonResp.buildSuccessResp(ls).toJsonString();
	}
	/**
	 * 回收站选中的删除
	 */
	@ResponseBody
	@RequestMapping(value = { "pitchOnRecycleDelete" })
	public String pitchOnRecycleDelete(String items) {
		String[] arr = items.split(",");
		for(String a:arr){
			KWord keyword = kWordService.queryById(Integer.parseInt(a));
			
			extraSpringHibernateTemplate.getHibernateTemplate().delete(keyword);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 回收站选中的恢复
	 */
	@ResponseBody
	@RequestMapping(value = { "pitchOnRecover" })
	public String pitchOnRecover(String items) {
		String[] arr = items.split(",");
		for(String a:arr){
			KWord keyword = kWordService.queryById(Integer.parseInt(a));
			keyword.setStatus(1);
			keyword.setRecoveryTime((long) 0);
			kWordService.updata(keyword);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 	pc后台删除选中的
	 */
	@ResponseBody
	@RequestMapping(value={"pitchOnDelete"})
	public String pitchOnDelete(String items){
		String[] arr = items.split(",");
		for(String a:arr){
			KWord entity = kWordService.queryById(Integer.parseInt(a));
			entity.setStatus(3);
			long recoveryTime=new Date().getTime();
			entity.setRecoveryTime(recoveryTime);
			kWordService.updata(entity);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 定时删除
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = { "timedDeletion" })
	public String timedDeletion() {
		long time=new Date().getTime();
		long time1=time-10*24*60*60*1000;
		List<KWord> ls =(List<KWord>) extraSpringHibernateTemplate.getHibernateTemplate().find("From KWord where recoveryTime>0 and recoveryTime<=?", time1);
		for(KWord k:ls){
			extraSpringHibernateTemplate.getHibernateTemplate().delete(k);
		}
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 进去回收站
	 */
	@ResponseBody
	@RequestMapping(value = { "intoRecycle" })
	public String intoRecycle(Integer kwordId) {
		KWord keyword = kWordService.queryById(kwordId);
		keyword.setStatus(3);
		long recoveryTime=new Date().getTime();
		keyword.setRecoveryTime(recoveryTime);
		kWordService.updata(keyword);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 回收站恢复
	 */
	@ResponseBody
	@RequestMapping(value = { "recover" })
	public String recover(Integer kwordId) {
		KWord keyword = kWordService.queryById(kwordId);
		keyword.setStatus(1);
		keyword.setRecoveryTime((long) 0);
		kWordService.updata(keyword);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 添加
	 */
	@ResponseBody
	@RequestMapping(value = { "addKeys" })
	public String add(String kwords, String content,Integer userId) {
		KWord keyword = new KWord();
		Long s=new Date().getTime();
		keyword.setKWords(kwords);
		keyword.setContent(content);
		keyword.setUserId(userId);
		kWordService.add(keyword);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	/**
	 * 安卓添加
	 */
	@ResponseBody
	@RequestMapping(value = { "androidadd" })
	public String androidadd(String kwords, String content,Integer userId) {
		List<KWord> allkowrd1 =(List<KWord>)extraSpringHibernateTemplate.getHibernateTemplate().find("From KWord where kwords=? and content=? and userId=? ", kwords,content,userId);
		if(allkowrd1.size()!=0){
			return CommonResp.buildErrorResp(BackendErrorCode.add_error).toJsonString();
		}
		KWord keyword = new KWord();
		Long s=new Date().getTime();
		keyword.setReleaseTime(s);
		keyword.setKWords(kwords);
		keyword.setContent(content);
		keyword.setUserId(userId);
		kWordService.add(keyword);
		return CommonResp.buildSuccessResp(keyword).toJsonString();
	}
	
	/**
	 * 查看所有
	 */
	@ResponseBody
	@RequestMapping(value = { "listAll" })
	public String list(HttpSession session) {
		List allkowrd =  kWordService.queryAll();
		return CommonResp.buildSuccessResp(allkowrd).toJsonString();
	}
	/**
	 * 查看所有该用户的
	 */
	@ResponseBody
	@RequestMapping(value = { "listAllUser" })
	public String listAllUser(Integer userId) {
		List<KWord> allkowrd =  kWordService.queryNotRecycleAll(userId);
		return CommonResp.buildSuccessResp(allkowrd).toJsonString();
	}
	/**
	 * 查看该用户所有的回收站的
	 */
	@ResponseBody
	@RequestMapping(value = { "listAllRecycle" })
	public String listAllRecycle(Integer userId) {
		List allkowrd =  kWordService.queryInRecycleAll(userId);
		return CommonResp.buildSuccessResp(allkowrd).toJsonString();
	}
	
	@ResponseBody
	@RequestMapping(value = { "list" })
	public String list(int pageIndex, int pageSize, HttpSession session) {
		pageIndex=pageIndex*pageSize;
		Paging<?> paging = extraSpringHibernateTemplate.findPage(poc, Order.desc("kwordId"),pageIndex, pageSize);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}

	/**
	 * 通过kWordId查询
	 */
	
	@ResponseBody
	@RequestMapping(value = { "queryById" })
	public String queryById(int id) {
		KWord kWord = kWordService.queryById(id);
		if (kWord == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		return CommonResp.buildSuccessResp(kWord).toJsonString();
	}

	/**
	 * 修改
	 */
		
	@ResponseBody
	@RequestMapping(value = { "edit" })
	public String edit(Integer id, String kwords, String content, HttpSession session) {
		KWord toUpdate = kWordService.queryById(id);
		if (toUpdate == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
	if (StringUtils.isNoneBlank(kwords)) {
			toUpdate.setKWords(Strings.trimAndNotNull(kwords));
		}
		if (StringUtils.isNoneBlank(content)) {
			toUpdate.setContent(Strings.trimAndNotNull(content));
		}
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
	
	/**
	 * 条件查询
	 */

	@ResponseBody
	@RequestMapping(value = "search")
	public String search(String kwords) throws ParseException {
		List<Criterion> criterions = new ArrayList<>();
		if (StringUtils.isNoneBlank(kwords)) {
			criterions.add(Restrictions.ilike("kwords", "%" + kwords + "%"));
		}
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("kwordId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}
	/**
	 * 条件查询该用户的
	 */
	@ResponseBody
	@RequestMapping(value = "queryRecycle")
	public String queryRecycle(String kwords, Integer userId) throws ParseException {
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("userId", userId));
		criterions.add(Restrictions.eq("status",3));
		if (StringUtils.isNoneBlank(kwords)) {
			criterions.add(Restrictions.ilike("kwords", "%" + kwords + "%"));
		}
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("kwordId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).
				toJsonString();
	}
	/**
	 * 条件查询该用户的
	 */
	@ResponseBody
	@RequestMapping(value = "searchUser")
	public String searchUser(String kwords, Integer userId) throws ParseException {
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("userId", userId));
		criterions.add(Restrictions.ne("status",3));
		if (StringUtils.isNoneBlank(kwords)) {
			criterions.add(Restrictions.ilike("kwords", "%" + kwords + "%"));
		}
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("kwordId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).
				toJsonString();
	}

	/**
	 * 删除
	 */
	
	@ResponseBody
	@RequestMapping(value = { "remove" })
	public String remove(int id) {
		KWord kWord = kWordService.queryById(id);
		if (kWord == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		extraSpringHibernateTemplate.getHibernateTemplate().delete(kWord);
		return CommonResp.buildSuccessResp().toJsonString();
	}
		
	
	/**
	 * 文件上传
	 */
	
	@ResponseBody
	
	@RequestMapping(value = { "save" })
	public String save(@RequestParam("file") MultipartFile file)throws Exception {
		KWord keyword = new KWord();
		String text = "";
		String kwords="";
		String countent="";
		        if(null!=file){
		        	String myFileName=file.getOriginalFilename();
		        	String suffixName=myFileName.substring(myFileName.lastIndexOf("."));
		        	if(suffixName.equals(".txt")){
		        		
		        		ByteArrayInputStream fileInputStrem=(ByteArrayInputStream)file.getInputStream();
		        		InputStreamReader isr=new InputStreamReader(fileInputStrem,"GBK");
		        		BufferedReader br=new BufferedReader(isr);
		        		String lineTxt;
		        		while((lineTxt=br.readLine())!=null){
		        			text=text+lineTxt;
		        		}
		        		  while(text.contains("<")){
		        			  	text=text.substring(text.indexOf("<")+1);
		        		       kwords=kwords+text.substring(0, text.indexOf(">"));
		        		       }
		        		  countent= text.substring(text.indexOf(">")+1);
		        		keyword.setKWords(kwords);
		        		keyword.setContent(countent);
		        		kWordService.add(keyword);
		        		br.close();
		        	}else {
		        		return CommonResp.buildErrorResp(BackendErrorCode.not_upload_error).toJsonString();
						
					}
		        }else {
		        	return CommonResp.buildErrorResp(BackendErrorCode.not_upload_error).toJsonString();
				}
		        
		        
		return CommonResp.buildSuccessResp().toJsonString();
	}
	
}
